-- userService存储用户的信息,并负责广播消息
local skynet = require "skynet"
local CMD = {}
local watchdog

-- username:fd
local users = {}
local agents = {}

-- 显示逻辑
local function printUsers()
    print("All users:")
    for k, v in pairs(users) do
        print(k .. " client fd:" .. v)
    end
end

-- 内部逻辑
local function isUserOnline(username)
    return users[username] ~= nil
end

local function getIdByUsername(username)
    return users[username]
end

-- 请求其他服务
local function updateAgents()
    agents = skynet.call(watchdog, "lua", "getAgents")
end

-- 响应其他服务
function CMD.broadcastRoomList()
    updateAgents()
    for fd, agent in pairs(agents) do
        skynet.call(agent, "lua", "sendRoomList")
    end
end

function CMD.getAgentByUsername(args)
    updateAgents()
    local username = args.username
    local fd = users[username]
    return agents[fd]
end

-- 玩家登录,记录username和fd
function CMD.login(args)
    local username = args.username
    local fd = args.fd
    if not isUserOnline(username) then
        users[username] = fd
        printUsers()
        return true
    else
        return false
    end
end

-- 登出
function CMD.logout(args)
    local username = args.username
    if username ~= nil then
        users[username] = nil
    end
end

-- 返回所有用户
function CMD.getUsers()
    local res = {}
    for k, v in pairs(users) do
        res[k] = k
    end
    return res
end

-- 返回所有在线用户
function CMD.getUsersOnline()
    local res = {}
    for k, v in pairs(usersOnline) do
        res[k] = k
    end
    return res
end

local function initUsers()
end

function CMD.start(conf)
    watchdog = skynet.queryservice("watchdog")
end

skynet.start(function()
    skynet.dispatch("lua", function(_, _, command, ...)
        local f = CMD[command]
        skynet.ret(skynet.pack(f(...)))
    end)
end)
